<template>
  <el-drawer v-model="visible" direction="rtl" width="400px">
    <template #header>
      <h4>{{ titleMap[drawerType] }}</h4>
    </template>
    <template #default>
      <el-form ref="elFormRef" :model="submitForm" label-width="80px">
        <el-form-item label="菜单名称">
          <el-input v-model="submitForm.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="submitForm.parent_id"
            :data="menuTree"
            check-strictly
            :props="{ label: 'title', value: 'id' }"
            :render-after-expand="false"
            clearable
          />
        </el-form-item>
        <el-form-item label="name">
          <el-input v-model="submitForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="path">
          <el-input v-model="submitForm.path" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="菜单地址">
          <el-input v-model="submitForm.file_path" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="submitForm.icon" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="closeDrawer">cancel</el-button>
        <el-button type="primary" @click="commitData">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts" name="MenuEditDrawer">
import { ref } from 'vue'
import { cloneDeep } from 'lodash'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { menuAddApi, menuEditApi } from '@/api/menu'

defineProps<{ menuTree: any[] }>()
const emit = defineEmits(['refresh'])
const titleMap = {
  add: '添加菜单',
  edit: '编辑菜单'
}

const drawerType = ref('')
const submitForm = ref<Record<string, any>>({})
const visible = ref(false)
const openDrawer = (type, row) => {
  drawerType.value = type
  visible.value = true
  submitForm.value = cloneDeep(row)
}

const elFormRef = ref<FormInstance>()
const commitData = async () => {
  // elFormRef.value?.validate(async valid => {
  //   if (valid) {
  //     return false
  //   }
  try {
    const { code, message } =
      drawerType.value === 'add'
        ? await menuAddApi(submitForm.value)
        : await menuEditApi(submitForm.value)
    if (code === 0) {
      ElMessage.success(message)
      closeDrawer(true)
    }
  } catch (error) {
    console.log(error)
  }
  // })
}

const closeDrawer = flag => {
  elFormRef.value?.resetFields()
  submitForm.value = {}
  visible.value = false
  if (typeof flag === 'boolean' && flag) {
    emit('refresh')
  }
}

defineExpose({
  openDrawer
})
</script>
